/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import controller.service.*;
import javax.swing.JTabbedPane;
import controller.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.entities.*;
import org.apache.poi.ss.usermodel.ExcelStyleDateFormatter;

/**
 *
 * @author K u Ku
 */
public class pnlCourse extends javax.swing.JPanel {

    CourseControllerService courseServiceCtrl = CourseController.getInstance();
    TeacherControllerService teacherServiceCtrl = TeacherController.getInstance();
    List<Course> courseList = courseServiceCtrl.getCourseList();
    
    /**
     * Creates new form pnlBase
     */
    public pnlCourse() {
        initComponents();
    }
    public pnlCourse(JTabbedPane tab) {
        initComponents();
        this.tab = tab;
        load(courseList);
        loadCboTeacher();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlList = new javax.swing.JPanel();
        pnlTable = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblData = new javax.swing.JTable();
        pnlSearch = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtSearch = new javax.swing.JTextField();
        cboSearch = new javax.swing.JComboBox();
        btnExport = new javax.swing.JButton();
        pnlDetails = new javax.swing.JPanel();
        pnlButton = new javax.swing.JPanel();
        btnClear = new javax.swing.JButton();
        btnInsert = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtID = new javax.swing.JTextField();
        txtName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        dcStart = new com.toedter.calendar.JDateChooser();
        jLabel5 = new javax.swing.JLabel();
        dcFinish = new com.toedter.calendar.JDateChooser();
        jLabel6 = new javax.swing.JLabel();
        txtDuration = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtNotes = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        cboTeacher = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        txtFees = new javax.swing.JTextField();

        setMinimumSize(new java.awt.Dimension(800, 500));
        setPreferredSize(new java.awt.Dimension(800, 500));
        setLayout(new java.awt.BorderLayout());

        pnlList.setLayout(new java.awt.BorderLayout());

        pnlTable.setLayout(new java.awt.BorderLayout());

        tblData.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblData.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblDataMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblData);

        pnlTable.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pnlList.add(pnlTable, java.awt.BorderLayout.CENTER);

        pnlSearch.setPreferredSize(new java.awt.Dimension(800, 30));
        pnlSearch.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel1.setText("Search");
        pnlSearch.add(jLabel1);

        txtSearch.setPreferredSize(new java.awt.Dimension(400, 20));
        pnlSearch.add(txtSearch);

        cboSearch.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "By ID", "By Name" }));
        cboSearch.setPreferredSize(new java.awt.Dimension(80, 20));
        pnlSearch.add(cboSearch);

        btnExport.setText("Export");
        btnExport.setMaximumSize(new java.awt.Dimension(80, 23));
        btnExport.setMinimumSize(new java.awt.Dimension(80, 23));
        btnExport.setPreferredSize(new java.awt.Dimension(80, 23));
        pnlSearch.add(btnExport);

        pnlList.add(pnlSearch, java.awt.BorderLayout.PAGE_START);

        add(pnlList, java.awt.BorderLayout.CENTER);

        pnlDetails.setPreferredSize(new java.awt.Dimension(800, 250));
        pnlDetails.setLayout(new java.awt.BorderLayout());

        pnlButton.setMinimumSize(new java.awt.Dimension(800, 30));
        pnlButton.setPreferredSize(new java.awt.Dimension(800, 30));
        pnlButton.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        btnClear.setText("Clear");
        btnClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearActionPerformed(evt);
            }
        });
        pnlButton.add(btnClear);

        btnInsert.setText("Insert");
        btnInsert.setPreferredSize(new java.awt.Dimension(80, 23));
        btnInsert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInsertActionPerformed(evt);
            }
        });
        pnlButton.add(btnInsert);

        btnUpdate.setText("Update");
        btnUpdate.setPreferredSize(new java.awt.Dimension(80, 23));
        pnlButton.add(btnUpdate);

        btnDelete.setText("Delete");
        btnDelete.setPreferredSize(new java.awt.Dimension(80, 23));
        pnlButton.add(btnDelete);

        btnClose.setText("Close");
        btnClose.setPreferredSize(new java.awt.Dimension(80, 23));
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });
        pnlButton.add(btnClose);

        pnlDetails.add(pnlButton, java.awt.BorderLayout.CENTER);

        jPanel2.setPreferredSize(new java.awt.Dimension(800, 220));

        jLabel2.setText("ID");

        txtID.setEnabled(false);
        txtID.setPreferredSize(new java.awt.Dimension(200, 20));

        txtName.setPreferredSize(new java.awt.Dimension(200, 20));

        jLabel3.setText("Name");

        jLabel4.setText("Start Date");

        dcStart.setPreferredSize(new java.awt.Dimension(200, 20));

        jLabel5.setText("Finish Date");

        dcFinish.setPreferredSize(new java.awt.Dimension(200, 20));

        jLabel6.setText("Duration");

        txtDuration.setPreferredSize(new java.awt.Dimension(200, 20));

        jLabel7.setText("Notes");

        txtNotes.setPreferredSize(new java.awt.Dimension(200, 20));

        jLabel8.setText("Teacher");

        cboTeacher.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboTeacher.setPreferredSize(new java.awt.Dimension(200, 20));

        jLabel9.setText("Fees");

        txtFees.setPreferredSize(new java.awt.Dimension(200, 20));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(dcStart, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(dcFinish, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtFees, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(32, 32, 32)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jLabel7)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jLabel6)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtNotes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtDuration, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cboTeacher, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(12, 12, 12))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtDuration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cboTeacher, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNotes, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtFees, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9))
                        .addGap(5, 5, 5)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(dcStart, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(25, 25, 25))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 5, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(dcFinish, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel5))))))
                .addContainerGap(87, Short.MAX_VALUE))
        );

        pnlDetails.add(jPanel2, java.awt.BorderLayout.PAGE_START);

        add(pnlDetails, java.awt.BorderLayout.PAGE_END);
    }// </editor-fold>//GEN-END:initComponents

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        tab.remove(this);
    }//GEN-LAST:event_btnCloseActionPerformed

    private void btnInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInsertActionPerformed
        insert();
        reload();
    }//GEN-LAST:event_btnInsertActionPerformed

    private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed
        clearComponents();
    }//GEN-LAST:event_btnClearActionPerformed

    private void tblDataMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblDataMouseClicked
        binding();
    }//GEN-LAST:event_tblDataMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClear;
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnExport;
    private javax.swing.JButton btnInsert;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JComboBox cboSearch;
    private javax.swing.JComboBox cboTeacher;
    private com.toedter.calendar.JDateChooser dcFinish;
    private com.toedter.calendar.JDateChooser dcStart;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel pnlButton;
    private javax.swing.JPanel pnlDetails;
    private javax.swing.JPanel pnlList;
    private javax.swing.JPanel pnlSearch;
    private javax.swing.JPanel pnlTable;
    private javax.swing.JTable tblData;
    private javax.swing.JTextField txtDuration;
    private javax.swing.JTextField txtFees;
    private javax.swing.JTextField txtID;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtNotes;
    private javax.swing.JTextField txtSearch;
    // End of variables declaration//GEN-END:variables
    JTabbedPane tab = new JTabbedPane();

    private void load(List<Course> courseList){
        DefaultTableModel dm = (DefaultTableModel) tblData.getModel();
        String columnsName[] = {"ID","Name","Fees","Start","Finish","Duration","Teacher","Notes"};
        dm.setColumnIdentifiers(columnsName);
        dm.setRowCount(0);
        for(Course c : courseList){
            String cell[] = new String[8];
            cell[0] = String.valueOf(c.getCourseID());
            cell[1] = c.getName();
            cell[2] = String.valueOf(c.getFees());
            cell[3] = String.valueOf(c.getStartDate());
            cell[4] = String.valueOf(c.getFinishDate());
            cell[5] = String.valueOf(c.getDuration());
            cell[6] = c.getTeacher().getName();
            cell[7] = c.getNotes();
            dm.addRow(cell);
        }
    }
    
    private void reload(){
        courseList = courseServiceCtrl.getCourseList();
        load(courseList);
        loadCboTeacher();
    }
    
    private void loadCboTeacher(){
        cboTeacher.removeAllItems();
        List<Teacher> listTeacher = teacherServiceCtrl.getTeachersList();
        for(Teacher c : listTeacher){
            cboTeacher.addItem(c.getTeacherID()+"-"+c.getName());
        }
    }
    
    private void clearComponents(){
        txtDuration.setText("");
        txtFees.setText("");
        txtID.setText("");
        txtName.setText("");
        txtNotes.setText("");
        txtSearch.setText("");
        dcStart.setDate(null);
        dcFinish.setDate(null);
    }
    
    private void binding(){
        int index = tblData.getSelectedRow();
        if(index > -1){
            String id = (String) tblData.getValueAt(index, 0);
            txtID.setText(id);
            txtName.setText((String) tblData.getValueAt(index, 1));
            txtFees.setText((String) tblData.getValueAt(index, 2));
            if(tblData.getValueAt(index, 3) != null){
                try {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    dcStart.setDate(df.parse((String) tblData.getValueAt(index, 3)));
                } catch (ParseException ex) {
                    Logger.getLogger(pnlCourse.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(tblData.getValueAt(index, 4) != null){
                try {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    dcFinish.setDate(df.parse((String) tblData.getValueAt(index, 4)));
                } catch (ParseException ex) {
                    Logger.getLogger(pnlCourse.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            txtDuration.setText((String) tblData.getValueAt(index, 5));
            int teacherId = courseServiceCtrl.getCourseByID(Integer.parseInt(id)).getTeacher().getTeacherID();
            String teacherName = courseServiceCtrl.getCourseByID(Integer.parseInt(id)).getTeacher().getName();
            cboTeacher.setSelectedItem(teacherId + "-" + teacherName);
            txtNotes.setText((String) tblData.getValueAt(index, 7));
        }
    }
    
    private void insert(){
        String name = txtName.getText();
        Double fees = Double.valueOf(txtFees.getText());
        Date sDate = dcStart.getDate();
        Date fDate = dcFinish.getDate();
        java.sql.Date startDate = new java.sql.Date(sDate.getTime());
        java.sql.Date finishDate = new java.sql.Date(fDate.getTime());
        float duration = Float.valueOf(txtDuration.getText());
        String strTeacher = cboTeacher.getSelectedItem().toString();
        String [] arrTeacher = strTeacher.split("-");
        int idTeacher = Integer.parseInt(arrTeacher[0]);
        System.out.println(idTeacher);
        Teacher t = teacherServiceCtrl.getTeacherByID(idTeacher);
        String notes = txtNotes.getText();
        Course c = new Course(1, name, fees, startDate, finishDate, duration, notes, t, true);
        if(courseServiceCtrl.insertCourse(c)){
            JOptionPane.showMessageDialog(this, "Insert success.");
        }
        else{
            JOptionPane.showMessageDialog(this, "Insert failed.");
        }
    }
}
